<?php

App::uses('AppModel', 'Model');

class User extends AppModel {

    public $table = 'users';
    public $actsAs = array('CakePtbr.AjusteData', 'CakePtbr.AjusteFloat', 'Search.Searchable');
    public $filterArgs = array(
        'id' => array('type' => 'value'),
        'role' => array('type' => 'like'),
        'name' => array('type' => 'like'),
        'username' => array('type' => 'like'),
        'password' => array('type' => 'like'),
        'active' => array('type' => 'value'),
        'created' => array('type' => 'like'),
        'modified' => array('type' => 'like'),
    );

    public function beforeSave($options = array()) {
        if (isset($this->data[$this->name]['password'])) {
            $this->data[$this->name]['password'] = AuthComponent::password($this->data[$this->name]['password']);
        }
        return true;
    }

    public $hasOne = array(
        'Client' => array(
            'className' => 'Client',
            'foreignKey' => 'user_id'
        )
    );

    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array(
        'username' => array(
            'UniqueUsername' => array(
                'rule' => array('checkUniqueUsername'),
                'required' => TRUE,
                'allowEmpty' => false,
                'message' => 'Usuário informado já existe.'
            ),
        ),
        'password' => array(
            'regra_1' => array(
                'on' => 'create',
                'rule' => array('notEmpty'),
                'last' => false
            ),
            'regra_2' => array(
                'rule' => array('between', 6, 25),
                'on' => 'create',
                'message' => 'Senha deve conter de 6 a 25 caracteres.'
            )
        ),
        'name' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
            ),
        )
    );

    public function checkUniqueUsername($data) {
        $isUnique = $this->find(
                'first', array(
            'fields' => array(
                'User.id',
                'User.username',
            ),
            'conditions' => array(
                'User.username' => $data['username']
            )
                )
        );

        if (!empty($isUnique)) {
            if (isset($this->data['User']['id'])) {
                if ($this->data['User']['id'] != '' AND $this->data['User']['id'] != $isUnique['User']['id']) {
                    return FALSE;
                }
            } else {
                return FALSE;
            }
        }
        return TRUE;
    }

}
